<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/14
 * Time: 23:16
 */

namespace app\api\controller;


use app\api\model\TransErr;
use app\api\service\Payment;
use think\Db;

class Callback
{
    //外网回调

    //支付宝
    const APPID = '2018120562488348';
    const PRIVATE_KEY = 'MIIEpAIBAAKCAQEA7TLBIBJPr1ILsW90fegpBbakxrXONLT5gc0jhvUw6+hfVuoTOjbCj+6940JkkLnJBaZJJfWbGSN1iSWi2hO5pTbHneWkOl+OIylHq8ATCoQippjB8a7Pbu4runlmHd2LYH2ZwuYvHuk84DQdWc3knGuLOcqCgQQIZ3rCj+IIjoE8bLpzGNOc2EE7bNtpdcVCDH44j1AEKj5SBSwTLrJiNDVSYF2slGtJEzSzss1uKFQ4wC6y4U+aho+RpSEOXydxb9SSx3nfW8LsDlsTzGsMa7+X8ZqRo/CBqyAGMIbvzyJaPu86LMyShm9TXK2obED0KQsVFXrldsjmepCZYEqxPQIDAQABAoIBAQCmp4hlXjg6eCzbB/ITHHDmIMN5EffFtHmxp04U3mT2+xcxW9kSh7L/qcAk0lsSDFae74xpbT0B1pYYPCdFjaJb4Dc0S0qt8MFPFwvSMmuucdRetOlfQ3FfAVwb8nu69BOfQeAsvcnRsBIjfLo6hJzhAfaaLhyvRQQaoHfe2/MjG3PqACVY5JLQnzyTvQw3W0axoQ2rF2ueX3kDvTGRIn+puidYxsjazhAa3LA6sA7uRx0zBiYHZQrGPMqWTENI/fgsKM18Bg/8Ak1xB9I7RsN25B6bI62mR19nKFa7ucJulRsk7i6j9/G0Bl6oz5/rVeaZcCW8wT8GSneqzR0M2VKJAoGBAPmYsTiWX33ARlN/DH/elcfnEaNtTZJ1NpziERFhhdwVOlDHeRaUB9NELRo6kT61q37lkNIRL/Jme6m9AKlQHostosyHA68Y3rjuwR6bBPglrLV1l3bAAQJjQL/Tvv7hxkn0QP5vTRtdsuNui/eXN+urIN1pbUI1AVXuWR3SgqZjAoGBAPNIogL2e+3IsvfsmSxN4O4VDtQRP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qxPQIDAQAB';


    //app支付验证异步通知
    public function alipayApppayNotify_old(){
        $param = input('post.');
        Payment::alipayApppaySuccess($param);exit;
//        file_put_contents(RUNTIME_PATH.'/alipayApppayNotifyPost.txt',json_encode($_POST,JSON_UNESCAPED_UNICODE));exit;
        file_put_contents(RUNTIME_PATH.'/alipayApppayNotifyPost.txt',json_encode(input('post.'),JSON_UNESCAPED_UNICODE));
        import('alipay.aop.AopClient', EXTEND_PATH, '.php');
        $param = input('post.');
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = self::PUBLIC_KEY;
        $flag = $aop->rsaCheckV1($param, NULL, "RSA2");
        file_put_contents(RUNTIME_PATH.'/alipayApppayNotifyFlag.txt',$flag);
        if ($flag){
            //TODO 支付成功
            Payment::alipayApppaySuccess($param);
            echo 'SUCCESS';
        }else{
            //todo 支付失败
            echo '失败';
        }
    }

    //app支付验证异步通知
    public function alipayApppayNotify(){
        $param = input('post.');

        if ($param['trade_status'] == 'TRADE_SUCCESS'){
            //TODO 支付成功
            Db::startTrans();
            try{
                Payment::alipayApppaySuccess($param);
                echo 'SUCCESS';
                Db::commit();
            }catch (\Exception $e){
                // 回滚事务
                Db::rollback();
                //记录异常
                TransErr::add($e);
            }
        }else{
            //todo 支付失败
            echo '失败';
        }
    }
}